using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Diagnostics;

namespace CGShaderIntegration.DrawableGameComponents
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class HeinzPatrikSunSystemComponent : Microsoft.Xna.Framework.DrawableGameComponent, IMatrices
    {
        ContentManager Content;
        SpriteBatch spriteBatch;
        Model sunModel;   //das 3D-Modell
        Model earthModel;   //das 3D-Modell
        Model moonModel;   //das 3D-Modell
        float aspectRatio;
        Boolean rotateRight = true;

        // Set the position of the model in world space, and set the rotation.
        Vector3 earthPosition = new Vector3(120, 0, 0);
        Vector3 sunPosition = Vector3.Zero;
        Vector3 moonPosition = new Vector3(35, 0, 0);
        float earthRotation = 0.0f;
        float moonRotation = 0.0f;

        //worldmatrixen
        public Matrix WorldMatrix { get; set; }
        public Matrix ViewMatrix { get; set; }
        public Matrix ProjectionMatrix { get; set; }
        Matrix sunWorldMatrix;
        Matrix earthWorldMatrix;
        Matrix moonWorldMatrix;

        //shader-effects
        Effect schachbrettShader;

        // Set the position of the camera in world space, for our view matrix.
        Vector3 cameraPosition = new Vector3(0.0f, 50.0f, 300.0f);

        public HeinzPatrikSunSystemComponent(Game game) : base(game)
        {
            this.Content = game.Content;
            this.aspectRatio = game.GraphicsDevice.Viewport.AspectRatio;
            game.Components.Add(this);
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        public override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            sunModel = Content.Load<Model>("models\\Sphere-I");
            earthModel = Content.Load<Model>("models\\Sphere-I");
            moonModel = Content.Load<Model>("models\\Sphere-I");

            //schachbrett-shader laden
            schachbrettShader = Content.Load<Effect>("effects\\HeinzPatrikSchachbrett");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Game.Exit();

            // TODO: Add your update logic here
            KeyboardState keybState = Keyboard.GetState();
            if (keybState.IsKeyDown(Keys.Left))
                rotateRight = false;
            if (keybState.IsKeyDown(Keys.Right))
                rotateRight = true;


            if (rotateRight)
            {
                earthRotation += (float)gameTime.ElapsedGameTime.TotalMilliseconds *
                MathHelper.ToRadians(0.025f);
                moonRotation += (float)gameTime.ElapsedGameTime.TotalMilliseconds *
                MathHelper.ToRadians(0.05f);
            }
            else
            {
                earthRotation -= (float)gameTime.ElapsedGameTime.TotalMilliseconds *
                MathHelper.ToRadians(0.025f);
                moonRotation -= (float)gameTime.ElapsedGameTime.TotalMilliseconds *
                MathHelper.ToRadians(0.05f);
            }
            
            
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Draw(GameTime gameTime)
        {
            //GraphicsDevice.Clear(Color.Black);

            //---------------------SUN----------------------------
            Matrix[] transformsSun = new Matrix[sunModel.Bones.Count];
            sunModel.CopyAbsoluteBoneTransformsTo(transformsSun);
            // Draw the model. A model can have multiple meshes, so loop.
            foreach (ModelMesh mesh in sunModel.Meshes)
            {
                // This is where the mesh orientation is set, as well 
                // as our camera and projection.           

                foreach (ModelMeshPart part in mesh.MeshParts)
                {
                    sunWorldMatrix = (Matrix.CreateScale(40f) * transformsSun[mesh.ParentBone.Index] * Matrix.CreateTranslation(sunPosition)) * WorldMatrix;

                    part.Effect = schachbrettShader;
                    part.Effect.Parameters["World"].SetValue(sunWorldMatrix);
                    part.Effect.Parameters["View"].SetValue(ViewMatrix);
                    part.Effect.Parameters["Projection"].SetValue(ProjectionMatrix);
                }

                // Draw the mesh, using the effects set above.
                mesh.Draw();
            }

            //---------------------EARTH----------------------------

            // TODO: Add your drawing code here
            // Copy any parent transforms.
            Matrix[] transformsEarth = new Matrix[earthModel.Bones.Count];
            earthModel.CopyAbsoluteBoneTransformsTo(transformsEarth);
            // Draw the model. A model can have multiple meshes, so loop.
            foreach (ModelMesh mesh in earthModel.Meshes)
            {
            //    // This is where the mesh orientation is set, as well 
            //    // as our camera and projection.
            
                foreach (ModelMeshPart part in mesh.MeshParts)
                {
                    earthWorldMatrix = (Matrix.CreateScale(14f) *
                        transformsEarth[mesh.ParentBone.Index] *
                        Matrix.CreateTranslation(earthPosition) *
                        Matrix.CreateRotationY(earthRotation)) *
                        WorldMatrix;

                    part.Effect = schachbrettShader;
                    part.Effect.Parameters["World"].SetValue(earthWorldMatrix);
                    part.Effect.Parameters["View"].SetValue(ViewMatrix);
                    part.Effect.Parameters["Projection"].SetValue(ProjectionMatrix);
                }
                // Draw the mesh, using the effects set above.
                mesh.Draw();
            }


            //---------------------MOON----------------------------

            // TODO: Add your drawing code here
            // Copy any parent transforms.
            Matrix[] transformsMoon = new Matrix[moonModel.Bones.Count];
            moonModel.CopyAbsoluteBoneTransformsTo(transformsMoon);
            // Draw the model. A model can have multiple meshes, so loop.
            foreach (ModelMesh mesh in moonModel.Meshes)
            {
                // This is where the mesh orientation is set, as well 
                // as our camera and projection.
                
                foreach (ModelMeshPart part in mesh.MeshParts)
                {
                    moonWorldMatrix = Matrix.CreateScale(2f) *
                        transformsMoon[mesh.ParentBone.Index] *
                        Matrix.CreateTranslation(moonPosition) *
                        Matrix.CreateRotationY(moonRotation);

                    //mond auf erdposition schieben
                    moonWorldMatrix = moonWorldMatrix *
                        Matrix.CreateTranslation(earthPosition) *
                        Matrix.CreateRotationY(earthRotation);

                    part.Effect = schachbrettShader;
                    part.Effect.Parameters["World"].SetValue(moonWorldMatrix);
                    part.Effect.Parameters["View"].SetValue(ViewMatrix);
                    part.Effect.Parameters["Projection"].SetValue(ProjectionMatrix);
                }


                // Draw the mesh, using the effects set above.
                mesh.Draw();
            }


            base.Draw(gameTime);
        }

        public String GetName()
        {
            return "HeinzPatrik";
        }
    }
}
